<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Android: NDK编程入门笔记 - Braincol - 博客园</title>
<link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/blog/css/common.css?id=20130704"/>
<link id="MainCss" type="text/css" rel="stylesheet" href="http://common.cnblogs.com/Skins/gray/style.css?id=20130704"/>
<link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/blog/css/common2.css"/>
<link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/css/shStyle.css"/>
<link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/hibraincol/rss"/>
<link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/hibraincol/rsd.xml"/>
<link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/hibraincol/wlwmanifest.xml"/>
<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script>  
<script type="text/javascript">
var currentBlogApp = 'hibraincol';
</script>
<script src="http://common.cnblogs.com/blog/script/common.js?id=20130704" type="text/javascript"></script> 
<script src="http://common.cnblogs.com/script/json2.js" type="text/javascript"></script>
<script type="text/javascript" src="http://common.cnblogs.com/script/syntaxHighlighter.js"></script>
</head>
<body>
<a name="top"></a>

<!--done-->
<div id="banner"><div id="bnr_pic">
<!--done-->
<div class="header">
	<div class="headerText">
		<a id="Header1_HeaderTitle" class="headermaintitle" href="http://www.cnblogs.com/hibraincol/">Hibraincol</a><br>
	</div>
	<div class="headerDis">快乐代码！</div>
</div>
</div></div>
<div id="main">
	<!-- left starts -->
	<div id="left">
	<div id="left_border">
		<DIV id="mystats">
			<br>
				
<!--done-->
<div class="blogStats">
随笔- 40&nbsp;
文章- 0&nbsp;
评论- 57&nbsp;

</div>
			
		</DIV>
		<div id="mylinks">
<!--done-->
<a id="MyLinks1_HomeLink" class="menu" href="http://www.cnblogs.com/">博客园</a>&nbsp;&nbsp;<a id="MyLinks1_MyHomeLink" class="menu" href="http://www.cnblogs.com/hibraincol/">首页</a>&nbsp;&nbsp;<a id="MyLinks1_NewPostLink" class="menu" rel="nofollow" href="http://www.cnblogs.com/hibraincol/admin/EditPosts.aspx?opt=1">新随笔</a>&nbsp;&nbsp;<a id="MyLinks1_NewArticleLink" class="menu" href="../../../../../EnterMyBlog.aspx?NewArticle=1">新文章</a>&nbsp;&nbsp;<a id="MyLinks1_ContactLink" accesskey="9" class="menu" rel="nofollow" href="http://space.cnblogs.com/msg/send/Braincol">联系</a>&nbsp;&nbsp;<a id="MyLinks1_Admin" class="menu" rel="nofollow" href="http://www.cnblogs.com/hibraincol/admin/EditPosts.aspx">管理</a>&nbsp;&nbsp;<a id="MyLinks1_Syndication" class="menu" href="http://www.cnblogs.com/hibraincol/rss">订阅</a>&nbsp;<a id="MyLinks1_XMLLink" href="http://www.cnblogs.com/hibraincol/rss"><img src="http://www.cnblogs.com/images/xml.gif" alt="订阅" /></a></div>
		<div id="topics">
			
	
<!--done-->
<div class = "post">
	<div class = "postTitle">
		<a id="cb_post_title_url" class="postTitle2" href="http://www.cnblogs.com/hibraincol/archive/2011/05/30/2063847.html">Android: NDK编程入门笔记</a>
	</div>
	<div id="cnblogs_post_body"><p><strong><font color="#000000" size="3">为何要用到NDK?</font></strong></p>  <p>概括来说主要分为以下几种情况：</p>  <blockquote>   <p><font color="#000000">1. 代码的保护，由于apk的java层代码很容易被反编译，而C/C++库反汇难度较大。</font></p>    <p><font color="#000000">2. 在NDK中调用第三方C/C++库，因为大部分的开源库都是用C/C++代码编写的。</font></p>    <p><font color="#000000">3. 便于移植，用C/C++写得库可以方便在其他的嵌入式平台上再次使用。</font></p>    <p><font color="#000000"></font></p> </blockquote>  <p><font color="#000000" size="3"><strong>下面就介绍下Android NDK的入门学习过程：</strong></font></p>  <p>入门的最好办法就是学习Android自带的例子， 这里就通过学习Android的NDK自带的demo程序：hello-jni来达到这个目的。</p>  <p><font color="#000000" size="3"><strong>一、 开发环境的搭建</strong></font></p>  <ol>   <li><font color="#000000">android的NDK开发需要在linux下进行： 因为需要把C/C++编写的代码生成能在arm上运行的.so文件，这就需要用到交叉编译环境，而交叉编译需要在linux系统下才能完成。</font> </li>    <li><font color="#000000">安装android-ndk开发包，这个开发包可以在google android 官网下载： 通过这个开发包的工具才能将android jni 的C/C++的代码编译成库</font> </li>    <li><font color="#000000">android应用程序开发环境： 包括eclipse、java、 android sdk、 adt等。</font> </li> </ol>  <p>如何下载和安装android-ndk我这里就不啰嗦了，安装完之后，需要将android-ndk的路劲加到环境变量PATH中：</p>  <blockquote>   <p><font color="#000000"><font style="background-color: #cccccc"></font></font><font color="#000000">sudo gedit /etc/environment</font></p> </blockquote>  <p>在environment的PATH环境变量中添加你的android-ndk的安装路劲，然后再让这个更改的环境变量立即生效：</p>  <blockquote>   <p><font style="background-color: #cccccc"></font>&#160;<font color="#000000">source&#160; /etc/environment</font></p> </blockquote>  <p>经过了上述步骤，在命令行下敲： </p>  <blockquote>   <p><font color="#000000"></font><font color="#000000">ndk-bulid</font></p> </blockquote>  <p>弹出如下的错误，而不是说ndk-build not found，就说明ndk环境已经安装成功了。</p>  <blockquote>   <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">Android NDK: Could not find application project directory !&#160;&#160;&#160; <br />Android NDK: Please define the NDK_PROJECT_PATH variable to point to it.&#160;&#160;&#160; <br />/home/braincol/workspace/android/android-ndk-r5/build/core/build-local.mk:85: *** Android NDK: Aborting&#160;&#160;&#160; .&#160; Stop.</font></p> </blockquote>  <p><strong></strong>&#160;</p>  <p><font color="#000000" size="3"><strong>二、代码的编写</strong></font></p>  <p><font color="#000000" size="3"><strong>1.首先是写java代码</strong></font></p>  <p>建立一个Android应用工程HelloJni，创建HelloJni.java文件：</p>  <p><em><font style="background-color: #cccccc"></font></em><em>HelloJni.java :</em></p>  <div id="codeSnippetWrapper">   <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">/*</span><br /><span style="color: #008000"> * Copyright (C) 2009 The Android Open Source Project</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span><br /><span style="color: #008000"> * you may not use this file except in compliance with the License.</span><br /><span style="color: #008000"> * You may obtain a copy of the License at</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> *      http://www.apache.org/licenses/LICENSE-2.0</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> * Unless required by applicable law or agreed to in writing, software</span><br /><span style="color: #008000"> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span><br /><span style="color: #008000"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span><br /><span style="color: #008000"> * See the License for the specific language governing permissions and</span><br /><span style="color: #008000"> * limitations under the License.</span><br /><span style="color: #008000"> */</span><br /><span style="color: #0000ff">package</span> com.example.hellojni;<br /><br /><span style="color: #0000ff">import</span> android.app.Activity;<br /><span style="color: #0000ff">import</span> android.widget.TextView;<br /><span style="color: #0000ff">import</span> android.os.Bundle;<br /><br /><br /><span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> HelloJni <span style="color: #0000ff">extends</span> Activity<br />{<br />    <span style="color: #008000">/** Called when the activity is first created. */</span><br />    @Override<br />    <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> onCreate(Bundle savedInstanceState)<br />    {<br />        <span style="color: #0000ff">super</span>.onCreate(savedInstanceState);<br /><br />        <span style="color: #008000">/* Create a TextView and set its content.</span><br /><span style="color: #008000">         * the text is retrieved by calling a native</span><br /><span style="color: #008000">         * function.</span><br /><span style="color: #008000">         */</span><br />        TextView  tv = <span style="color: #0000ff">new</span> TextView(<span style="color: #0000ff">this</span>);<br />        tv.setText( stringFromJNI() );<br />        setContentView(tv);<br />    }<br /><br />    <span style="color: #008000">/* A native method that is implemented by the</span><br /><span style="color: #008000">     * 'hello-jni' native library, which is packaged</span><br /><span style="color: #008000">     * with this application.</span><br /><span style="color: #008000">     */</span><br />    <span style="color: #0000ff">public</span> <span style="color: #0000ff">native</span> String  stringFromJNI();<br /><br />    <span style="color: #008000">/* This is another native method declaration that is *not*</span><br /><span style="color: #008000">     * implemented by 'hello-jni'. This is simply to show that</span><br /><span style="color: #008000">     * you can declare as many native methods in your Java code</span><br /><span style="color: #008000">     * as you want, their implementation is searched in the</span><br /><span style="color: #008000">     * currently loaded native libraries only the first time</span><br /><span style="color: #008000">     * you call them.</span><br /><span style="color: #008000">     *</span><br /><span style="color: #008000">     * Trying to call this function will result in a</span><br /><span style="color: #008000">     * java.lang.UnsatisfiedLinkError exception !</span><br /><span style="color: #008000">     */</span><br />    <span style="color: #0000ff">public</span> <span style="color: #0000ff">native</span> String  unimplementedStringFromJNI();<br /><br />    <span style="color: #008000">/* this is used to load the 'hello-jni' library on application</span><br /><span style="color: #008000">     * startup. The library has already been unpacked into</span><br /><span style="color: #008000">     * /data/data/com.example.HelloJni/lib/libhello-jni.so at</span><br /><span style="color: #008000">     * installation time by the package manager.</span><br /><span style="color: #008000">     */</span><br />    <span style="color: #0000ff">static</span> {<br />        System.loadLibrary(<span style="color: #006080">&quot;hello-jni&quot;</span>);<br />    }<br />}</pre>

  <br /></div>

<p>这段代码很简单，注释也很清晰，这里只提两点：<font color="#000000">:</font></p>

<blockquote>
  <p><font color="#000000">static{ 
      <br />System.loadLibrary(<span style="color: #006080">&quot;hello-jni&quot;</span>); 

      <br />}</font></p>
</blockquote>

<p><font style="background-color: #ffffff" color="#000000">表明程序开始运行的时候会加载hello-jni, static区声明的代码会先于onCreate方法执行。如果你的程序中有多个类，而且如果HelloJni这个类不是你应用程序的入口，那么hello-jni（完整的名字是libhello-jni.so）这个库会在第一次使用HelloJni这个类的时候加载。</font></p>

<blockquote>
  <p><font color="#000000">public native String stringFromJNI(); 
      <br />public native String unimplementedStringFromJNI(); </font><font color="#000000"></font></p>
  <font color="#000000"></font></blockquote>

<p><font color="#000000">可以看到这两个方法的声明中有 native 关键字， 这个关键字表示这两个方法是本地方法，也就是说这两个方法是通过本地代码（C/C++）实现的，在java代码中仅仅是声明。</font></p>

<p>用eclipse编译该工程，生成相应的.class文件，这步必须在下一步之前完成，因为生成.h文件需要用到相应的.class文件。</p>

<p>&#160;</p>

<p><strong><font color="#000000" size="3">2. 编写相应的C/C++代码</font></strong></p>

<p>刚开始学的时候，有个问题会让人很困惑，相应的C/C++代码如何编写，函数名如何定义？ 这里讲一个方法，利用javah这个工具生成相应的.h文件，然后根据这个.h文件编写相应的C/C++代码。</p>

<p><strong><font color="#000000">2.1 生成相应.h文件：</font></strong></p>

<p>就拿我这的环境来说，首先在终端下进入刚刚建立的HelloJni工程的目录：</p>

<blockquote>
  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">braincol@ubuntu:~$ cd workspace/android/NDK/hello-jni/ </font><font style="background-color: #cccccc" color="#000000"></font></p>
</blockquote>
ls查看工程文件 

<blockquote>
  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls 
      <br />AndroidManifest.xml&#160; assets&#160; bin&#160; default.properties&#160; gen&#160; res&#160; src</font><font color="#d16349"> 
      <br /></font><font color="#d16349"></font></p>
</blockquote>

<p>可以看到目前仅仅有几个标准的android应用程序的文件（夹）。</p>

<p>首先我们在工程目录下建立一个jni文件夹：</p>

<blockquote>
  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ mkdir jni 
      <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls 

      <br />AndroidManifest.xml&#160; assets&#160; bin&#160; default.properties&#160; gen&#160; jni&#160; res&#160; src 

      <br /></font><font style="background-color: #cccccc" color="#000000"></font></p>
</blockquote>
<font color="#333333"></font>

<p>下面就可以生成相应的.h文件了：</p>

<blockquote>
  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ javah -classpath bin -d jni com.example.hellojni.HelloJni 
      <br /></font><font style="background-color: #cccccc" color="#000000"></font></p>
</blockquote>

<p>-classpath bin：表示类的路劲</p>

<p>-d jni: 表示生成的头文件存放的目录</p>

<p>com.example.hellojni.HelloJni 则是完整类名</p>

<p>这一步的成功要建立在已经在 bin/com/example/hellojni/&#160; 目录下生成了 HelloJni.class的基础之上。</p>

<p>现在可以看到jni目录下多了个.h文件：</p>

<blockquote>
  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000"></font><font color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ cd jni/ 
      <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni/jni$ ls 

      <br /></font><font color="#000000">com_example_hellojni_HelloJni.h</font></p>
</blockquote>
<font color="#c0504d">
  <p><font color="#000000">我们来看看com_example_hellojni_HelloJni.h的内容：</font></p>

  <p><em><font style="background-color: #cccccc" color="#000000"></font></em><em><font color="#000000">com_example_hellojni_HelloJni.h : </font></em></p>
</font><font color="#c0504d">
  <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">/* DO NOT EDIT THIS FILE - it is machine generated */</span><br /><span style="color: #cc6633">#include</span> &lt;jni.h&gt;<br /><span style="color: #008000">/* Header for class com_example_hellojni_HelloJni */</span><br /><br /><span style="color: #cc6633">#ifndef</span> _Included_com_example_hellojni_HelloJni<br /><span style="color: #cc6633">#define</span> _Included_com_example_hellojni_HelloJni<br /><span style="color: #cc6633">#ifdef</span> __cplusplus<br /><span style="color: #0000ff">extern</span> <span style="color: #006080">&quot;C&quot;</span> {<br /><span style="color: #cc6633">#endif</span><br /><span style="color: #008000">/*</span><br /><span style="color: #008000"> * Class:     com_example_hellojni_HelloJni</span><br /><span style="color: #008000"> * Method:    stringFromJNI</span><br /><span style="color: #008000"> * Signature: ()Ljava/lang/String;</span><br /><span style="color: #008000"> */</span><br />JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI<br />  (JNIEnv *, jobject);<br /><br /><span style="color: #008000">/*</span><br /><span style="color: #008000"> * Class:     com_example_hellojni_HelloJni</span><br /><span style="color: #008000"> * Method:    unimplementedStringFromJNI</span><br /><span style="color: #008000"> * Signature: ()Ljava/lang/String;</span><br /><span style="color: #008000"> */</span><br />JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI<br />  (JNIEnv *, jobject);<br /><br /><span style="color: #cc6633">#ifdef</span> __cplusplus<br />}<br /><span style="color: #cc6633">#endif</span><br /><span style="color: #cc6633">#endif</span></pre>

  <p><font color="#000000">上面代码中的JNIEXPORT 和 JNICALL 是jni的宏，在android的jni中不需要，当然写上去也不会有错。</font></p>

  <p><font color="#000000">从上面的源码中可以看出这个函数名那是相当的长啊。。。。 不过还是很有规律的， 完全按照：java_pacakege_class_mathod 形式来命名。</font></p>

  <p><font color="#000000">也就是说：</font></p>

  <p><font color="#ffffff"></font></p>

  <blockquote>
    <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">Hello.java中 stringFromJNI() 方法对应于 C/C++中的 Java_com_example_hellojni_HelloJni_stringFromJNI() 方法</font></p>

    <p><font color="#000000">HelloJni.java中的 unimplementedStringFromJNI() 方法对应于 C/C++中的 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI() 方法 
        <br /></font><font style="background-color: #cccccc" color="#000000"></font></p>
  </blockquote>

  <p><font color="#000000">注意下其中的注释：</font></p>

  <blockquote>
    <p><font color="#000000"><font style="background-color: #cccccc"><span style="color: #008000"><font color="#000000"></font></span></font></font><font color="#000000"><span style="color: #008000"><font color="#000000">Signature: ()Ljava/lang/String;</font></span> 

        <br /></font><font color="#000000"><font style="background-color: #cccccc"></font></font></p>
  </blockquote>

  <p><font color="#000000">()Ljava/lang/String;</font></p>

  <p><font color="#000000">()表示函数的参数为空（这里为空是指除了JNIEnv *, jobject 这两个参数之外没有其他参数，JNIEnv*, jobject是所有jni函数必有的两个参数，分别表示jni环境和对应的java类（或对象）本身），</font></p>

  <p><font color="#000000">Ljava/lang/String; 表示函数的返回值是java的String对象。</font></p>

  <p>&#160;</p>

  <p><font color="#000000"><strong>2.2 编写相应的.c文件：</strong></font></p>

  <p><em><font style="background-color: #cccccc" color="#000000"></font></em><em><font color="#000000">hello-jni.c :</font></em></p>
</font><font color="#c0504d">
  <div id="codeSnippetWrapper">
    <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000">/*</span><br /><span style="color: #008000"> * Copyright (C) 2009 The Android Open Source Project</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span><br /><span style="color: #008000"> * you may not use this file except in compliance with the License.</span><br /><span style="color: #008000"> * You may obtain a copy of the License at</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> *      http://www.apache.org/licenses/LICENSE-2.0</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> * Unless required by applicable law or agreed to in writing, software</span><br /><span style="color: #008000"> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span><br /><span style="color: #008000"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span><br /><span style="color: #008000"> * See the License for the specific language governing permissions and</span><br /><span style="color: #008000"> * limitations under the License.</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> */</span><br /><span style="color: #cc6633">#include</span> &lt;string.h&gt;<br /><span style="color: #cc6633">#include</span> &lt;jni.h&gt;<br /><br /><span style="color: #008000">/* This is a trivial JNI example where we use a native method</span><br /><span style="color: #008000"> * to return a new VM String. See the corresponding Java source</span><br /><span style="color: #008000"> * file located at:</span><br /><span style="color: #008000"> *</span><br /><span style="color: #008000"> *   apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java</span><br /><span style="color: #008000"> */</span><br />jstring<br />Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,<br />                                                  jobject thiz )<br />{<br />    <span style="color: #0000ff">return</span> (*env)-&gt;NewStringUTF(env, <span style="color: #006080">&quot;Hello from JNI !&quot;</span>);<br />}</pre>
  </div>

  <p><font color="#000000">这里只是实现了Java_com_example_hellojni_HelloJni_stringFromJNI方法，而 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI 方法并没有实现，因为在HelloJni.java中只调用了stringFromJNI()方法，所以unimplementedStringFromJNI()方法没有实现也没关系，不过建议最好还是把所有java中定义的本地方法都实现了，写个空函数也行啊。。。有总比没有好。</font></p>

  <p><font color="#000000">Java_com_example_hellojni_HelloJni_stringFromJNI() 函数只是简单的返回了一个内容为 &quot;Hello from JNI !&quot; 的jstring对象（对应于java中的String对象）。</font></p>

  <p><font color="#000000">hello-jni.c文件已经编写好了，现在可以把com_example_hellojni_HelloJni.h文件给删了，当然留着也行，只是我还是习惯把不需要的文件给清理干净了。</font></p>

  <p><font color="#000000"></font>&#160;</p>

  <p><strong><font color="#000000" size="3">3. 编译hello-jni.c 生成相应的库</font></strong></p>

  <p><font color="#000000"><strong>3.1 编写Android.mk文件</strong></font></p>

  <p><font color="#000000">在jni目录下（即hello-jni.c 同级目录下）新建一个Android.mk文件，<font style="background-color: #cccccc"></font></font><font color="#000000">Android.mk </font><font color="#000000"><font style="background-color: #cccccc"></font>文件是Android 的 makefile文件，内容如下：</font></p>

  <div>
    <pre style="border-bottom-style: none; text-align: left; padding-bottom: 0px; line-height: 12pt; border-right-style: none; background-color: #f4f4f4; margin: 0em; padding-left: 0px; width: 100%; padding-right: 0px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; border-top-style: none; color: black; font-size: 8pt; border-left-style: none; overflow: visible; padding-top: 0px" id="codeSnippet"><span style="color: #008000"># Copyright (C) 2009 The Android Open Source Project</span><br /><span style="color: #008000">#</span><br /><span style="color: #008000"># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span><br /><span style="color: #008000"># you may not use this file except in compliance with the License.</span><br /><span style="color: #008000"># You may obtain a copy of the License at</span><br /><span style="color: #008000">#</span><br /><span style="color: #008000">#      http://www.apache.org/licenses/LICENSE-2.0</span><br /><span style="color: #008000">#</span><br /><span style="color: #008000"># Unless required by applicable law or agreed to in writing, software</span><br /><span style="color: #008000"># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span><br /><span style="color: #008000"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span><br /><span style="color: #008000"># See the License for the specific language governing permissions and</span><br /><span style="color: #008000"># limitations under the License.</span><br /><span style="color: #008000">#</span><br />LOCAL_PATH := $(call my-dir)<br /><br /><span style="color: #0000ff">include</span> $(CLEAR_VARS)<br /><br />LOCAL_MODULE    := hello-jni<br />LOCAL_SRC_FILES := hello-jni.c<br /><br /><span style="color: #0000ff">include</span> $(BUILD_SHARED_LIBRARY)</pre>
  </div>

  <div><font color="#ffffff">这个Androd.mk文件很短，下面我们来逐行解释下：</font></div>

  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">LOCAL_PATH := $(call my-dir) </font></p>
</font><font color="#c0504d">
  <blockquote>
    <p><font color="#000000">一个Android.mk 文件首先必须定义好LOCAL_PATH变量。它用于在开发树中查找源文件。在这个例子中，宏函数’my-dir’, 由编译系统提供，用于返回当前路径（即包含Android.mk file文件的目录）。</font></p>
  </blockquote>

  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">include $( CLEAR_VARS) </font></p>
</font><font color="#c0504d">
  <blockquote>
    <p><font color="#000000">CLEAR_VARS由编译系统提供，指定让GNU MAKEFILE为你清除许多LOCAL_XXX变量（例如 LOCAL_MODULE, LOCAL_SRC_FILES, LOCAL_STATIC_LIBRARIES, 等等...), 
        <br />除LOCAL_PATH 。这是必要的，因为所有的编译控制文件都在同一个GNU MAKE执行环境中，所有的变量都是全局的。</font></p>
  </blockquote>

  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">LOCAL_MODULE := hello-jni</font></p>
</font><font color="#c0504d">
  <blockquote>
    <p><font color="#000000">编译的目标对象，LOCAL_MODULE变量必须定义，以标识你在Android.mk文件中描述的每个模块。名称必须是唯一的，而且不包含任何空格。</font></p>

    <p><font color="#000000">注意：编译系统会自动产生合适的前缀和后缀，换句话说，一个被命名为'hello-jni'的共享库模块，将会生成'libhello-jni.so'文件。 </font></p>

    <p><font color="#000000">重要注意事项： </font></p>

    <p><font color="#000000">如果你把库命名为‘libhello-jni’，编译系统将不会添加任何的lib前缀，也会生成 'libhello-jni.so'，这是为了支持来源于Android平台的源代码的Android.mk文件，如果你确实需要这么做的话。</font></p>
  </blockquote>

  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">LOCAL_SRC_FILES := hello-jni.c</font></p>
</font><font color="#c0504d">
  <blockquote>
    <p><font color="#000000">LOCAL_SRC_FILES变量必须包含将要编译打包进模块中的C或C++源代码文件。注意，你不用在这里列出头文件和包含文件，因为编译系统将会自动为你找出依赖型的文件；仅仅列出直接传递给编译器的源代码文件就好。 </font></p>

    <p><font color="#000000">注意，默认的C++源码文件的扩展名是’.cpp’. 指定一个不同的扩展名也是可能的，只要定义LOCAL_DEFAULT_CPP_EXTENSION变量，不要忘记开始的小圆点（也就是’.cxx’,而不是’cxx’）</font></p>
  </blockquote>

  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">include $(BUILD_SHARED_LIBRARY) </font></p>
</font><font color="#c0504d">
  <blockquote>
    <p><font color="#000000">BUILD_SHARED_LIBRARY表示编译生成共享库，是编译系统提供的变量，指向一个GNU Makefile脚本，负责收集自从上次调用'include $(CLEAR_VARS)'以来，定义在LOCAL_XXX变量中的所有信息，并且决定编译什么，如何正确地去做。还有 BUILD_STATIC_LIBRARY变量表示生成静态库：lib$(LOCAL_MODULE).a， BUILD_EXECUTABLE 表示生成可执行文件。</font></p>
  </blockquote>

  <div>&#160;</div>

  <div><strong><font color="#000000">3.2 生成.so共享库文件</font></strong></div>

  <div><font color="#000000">Andro文件已经编写好了，现在可以用android NDK开发包中的 ndk-build脚本生成对应的.so共享库了，方法如下：</font></div>

  <blockquote>
    <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni/jni$ cd .. 
        <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls 

        <br />AndroidManifest.xml&#160; assets&#160; bin&#160; default.properties&#160; gen&#160; jni&#160; libs&#160; obj&#160; res&#160; src 

        <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ndk-build 

        <br />Gdbserver&#160;&#160;&#160;&#160;&#160; : [arm-linux-androideabi-4.4.3] libs/armeabi/gdbserver 

        <br />Gdbsetup&#160;&#160;&#160;&#160;&#160;&#160; : libs/armeabi/gdb.setup 

        <br />Install&#160;&#160;&#160;&#160;&#160;&#160;&#160; : libhello-jni.so =&gt; libs/armeabi/libhello-jni.so 

        <br /></font><font style="background-color: #cccccc" color="#000000"></font></p>
  </blockquote>
</font>

<p>可以看到已经正确的生成了libhello-jni.so共享库了， 我们去 libs/armeabi/ 目录下看看：</p>

<blockquote>
  <p><font style="background-color: #cccccc" color="#000000"></font><font color="#000000">braincol@ubuntu:~/workspace/android/NDK/hello-jni$ cd libs/ 
      <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs$ ls 

      <br />armeabi 

      <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs$ cd armeabi/ 

      <br />braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs/armeabi$ ls 

      <br />gdbserver&#160; gdb.setup&#160; libhello-jni.so</font></p>
</blockquote>

<p><strong><font color="#000000" size="3">4. 在eclipse重新编译HelloJni工程，生成apk</font></strong></p>

<p>eclipse中刷新下HelloJni工程，重新编译生成apk，libhello-jni.so共享库会一起打包在apk文件内。</p>

<p>在模拟器中看看运行结果：</p>

<p><font color="#c0504d"><a href="http://images.cnblogs.com/cnblogs_com/hibraincol/201105/201105302329215965.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="hello-jni" border="0" alt="hello-jni" src="http://images.cnblogs.com/cnblogs_com/hibraincol/201105/201105302329223390.png" width="318" height="388" /></a></font></p>

<p><font color="#c0504d">
    <br /></font></p></div><div id="MySignature"></div>
<script type="text/javascript">
var isLogined = false;
var cb_blogId = 75839;
var cb_entryId = 2063847;
var cb_blogApp = currentBlogApp;
var cb_blogUserGuid = "b6df09fc-38bf-df11-ac81-842b2b196315";
var cb_entryCreatedDate = '2011/5/30 23:29:00';
var enableGoogleAd = true;
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
</script>
<div class="clear"></div>
<div id="blog_post_info_block">
<div id="blog_post_info">
</div>
<div class="clear"></div>
<div id="post_next_prev"></div>
</div>
<script type="text/javascript">
    //SyntaxHighlighter.config.strings.expandSource = '<span><img src="http://static.cnblogs.com/images/expand-code.gif" alt="" class="expand-code-icon"/>View Code</span>';
    $(function () {  
        loadViewCount(cb_entryId);
        fixPostBodyFormat();
        loadAdUnderPost();
        loadBlogSignature();
        LoadPostInfoBlock(cb_blogId, cb_entryId, cb_blogApp, cb_blogUserGuid);
        GetPrevNextPost(cb_entryId, cb_blogId, cb_entryCreatedDate);        
        GetHistoryToday(cb_blogId, cb_blogApp, cb_entryCreatedDate);        
    });
</script>
	<div class = "postDesc"><img src="/skins/gray/images/speech.gif" align="absmiddle" />&nbsp;posted on <span id="post-date">2011-05-30 23:29</span> <a href='http://www.cnblogs.com/hibraincol/'>Braincol</a> 阅读(<span id="post_view_count">...</span>) 评论(<span id="post_comment_count">...</span>)  <a href ="http://www.cnblogs.com/hibraincol/admin/EditPosts.aspx?postid=2063847" rel="nofollow">编辑</a> <a href="#" onclick="AddToWz(2063847);return false;">收藏</a></div>
</div>
<script src="http://counter.cnblogs.com/blog/post/2063847" type="text/javascript"></script>

<div id="blog-comments-placeholder"></div><script type="text/javascript">var commentManager = new blogCommentManager();commentManager.renderComments(0);</script>
<div id="comment_form" class="commentform">
<div id="divCommentShow"></div>
<div id="comment_nav"><span id="span_refresh_tips"></span><a href="javascript:void(0);" id="lnk_RefreshComments" onclick="return RefreshCommentList();">刷新评论</a><a href="#" onclick="return RefreshPage();">刷新页面</a><a href="#top">返回顶部</a></div>
<div id="comment_form_container"></div>

<script type="text/javascript">
    if (typeof commentManager === 'undefined') {
        commentManager = new blogCommentManager();
    }
    commentManager.loadCommentForm();   
</script>

<div class="ad_text_commentbox" id="ad_text_under_commentbox"></div>
<div id="site_nav_under"><a href="http://www.cnblogs.com/" target="_blank" title="程序员的网上家园">博客园首页</a><a href="http://q.cnblogs.com/" target="_blank" title="程序员问答社区">博问</a><a href="http://news.cnblogs.com/" target="_blank" title="IT新闻">新闻</a><a href="http://home.cnblogs.com/ing/" target="_blank">闪存</a><a href="http://job.cnblogs.com/" target="_blank">程序员招聘</a><a href="http://kb.cnblogs.com/" target="_blank">知识库</a></div>
<div id="ad_under_post_holder"></div>
<div id="HistoryToday" class="c_ad_block"></div>
</div>





		</div>
	</div>
	</div>
	<!-- left ends -->
	<!-- right starts -->
	<div id="right">
		<!-- 右侧工具部分 -->
		<div id="right_content">
	
			
<!--done-->
<h1 class="listtitle" style="padding-top:14px;padding-left:42px;">公告</h1>
<div class="newsItem">
	<div id="blog-news"></div>
</div>

	
			<div id="calendar"><div id="blog-calendar-block" style="display:none"><div id="blog-calendar"></div>
</div></div>
			
				<DIV id="leftcontentcontainer">
					<div id="blog-sidecolumn"></div>
				</DIV>
			
		</div>
		<!-- //右侧工具部分 -->
	</div>
	<!-- right ends -->
	<div class="clear"></div>
</div>
<div id="footer">
<!--done-->
Copyright &copy;2013 Braincol</div>

<script type="text/javascript" src="http://common.cnblogs.com/script/google-analytics.js"></script>
</body>
</html>
